/*
 * @Author: youngqj youngqj@126.com
 * @Date: 2024-10-21 19:05:03
 * @LastEditors: youngqj youngqj@126.com
 * @LastEditTime: 2024-12-03 18:33:04
 * @FilePath: /mallSystem/core/utils/response.go
 * @Description:
 *
 * Copyright © Zhejiang Xiaoqu Information Technology Co., Ltd, All Rights Reserved.
 */
package utils

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 统一的响应格式
type Response struct {
	Code    int         `json:"code"`    // 自定义状态码
	Message string      `json:"message"` // 消息
	Data    interface{} `json:"data"`    // 数据
}

type Pagination struct {
	Total       int `json:"total"`
	CurrentPage int `json:"current_page"`
	TotalPage   int `json:"total_page"`
	PageSize    int `json:"page_size"`
}

type ResponseWithPage struct {
	Code       int         `json:"code"`
	Message    string      `json:"message"`
	Data       interface{} `json:"data"`
	Pagination *Pagination `json:"pagination,omitempty"`
}

// responseWithData 有数据返回
func ResponseWithData(c *gin.Context, data interface{}, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    200,
		Message: message,
		Data:    data,
	})
}

// responseNilData 没有数据返回
func ResponseNilData(c *gin.Context, code int, message string) {
	c.JSON(code, Response{
		Code:    code,
		Message: message,
		Data:    nil,
	})

}
func RetSucess(c *gin.Context, message string) {
	//c.JSON(200,ResponseNilData())
	ResponseNilData(c, 200, message)
}

func ResponseWithPageInfo(c *gin.Context, data interface{}, message string, total, page, pageSize int) {
	pages := calculateTotalPages(total, pageSize)
	c.JSON(http.StatusOK, ResponseWithPage{
		Code:    200,
		Message: message,
		Data:    data,
		Pagination: &Pagination{
			Total:       total,
			TotalPage:   pages,
			CurrentPage: page,
			PageSize:    pageSize,
		},
	})
}

func calculateTotalPages(totalItems int, itemsPerPage int) int {
	totalPages := totalItems / itemsPerPage
	if totalItems%itemsPerPage > 0 {
		totalPages++
	}
	return totalPages
}
